<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>开始游戏</title>

    <!-- Bootstrap -->
    <link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->


    <script src="js/jquery-3.2.1.min.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

    <script type="text/javascript">
        //页面中统一规定，石头为0，剪刀为1，布为2
        var uid = location.search.substr(4).split("&")[0];
        var hid = location.search.substr(4).split("&")[1].split("=")[1];
        var g_wj_num = 99;
        var g_round_num = 99;
        var websocket_msg_patt = /{.+flag.+}/i;
        var is_ready=0;

        function combatscore_add() {

            $.ajax({
                type: "GET",
                dataType: "json",
                url: "../api/game/combatscore/add?id=" + uid,
                success: function (msg) {
                    //alert(msg.code);
                    console.info(msg.message);
                    initTitleDate();
                }
            });
        }

        function combatscore_update(code) {

            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "../api/game/combatscore/update",
                data: '{"id":"' + uid + '","code":"' + code + '","random":' + Math.random() + '}',

                success: function (msg) {
                    //alert(msg.code);
                    console.info(msg.code);
                    initTitleDate();
                    $('a').removeAttr("disabled");
                }
            });
        }


        function initTitleDate() {
            $.ajax({
                type: "GET",
                url: "../api/game/combatscore/query",
                data: {
                    "id": uid, "random": Math.random()
                },
                dataType: "json",
                success: function (msg) {
                    //alert(msg.code);
                    console.info(msg.data);
                    var total = msg.data.total;
                    var win = msg.data.win;
                    $("#total").text(total);
                    $("#win").text(win);
                }
            });
            $.ajax({
                type: "GET",
                url: "../loginOnline.html?random=" + Math.random(),
                dataType: "json",
                success: function (msg) {
                    //alert(msg.code);
                    var totalonline = msg.data;
                    $("#totalonline").text(totalonline);
                }
            });
        }

        //发送玩家出拳消息
        function send_num(wj_num) {
            $('a').attr('disabled', "true");
            g_wj_num = wj_num;
            ws.send('{"flag":"2","data":{"code":"' + wj_num + '","userId":"' + uid + '","roomId":"' + hid + '"}}');
            if (g_round_num != 99) {
                iswin(g_wj_num, g_round_num);
            }
        }

        //发送玩家退出消息
        function send_exit() {
            $('a').attr('disabled', "true");
            ws.send('{"flag":"3","data":{"userId":"' + uid + '","roomId":"' + hid + '"}}');
            $.ajax({
                type: "POST",
                contentType:"application/json",
                url: "../api/game/combathouse/update",
                data: '{"userId":"'+uid+'","roomId":"'+hid+'","opt":"2"}',
                success: function (msg) {
                    //alert(msg.code);;
                    window.location.href = "selecthouse.html?id="+uid;
                }
            });
        }

        //发送玩家准备消息
        function send_ready() {
            $('a').attr('disabled', "true");
            ws.send('{"flag":"1","data":{"userId":"' + uid + '","roomId":"' + hid + '"}}');
        }

        //判断胜负
        function iswin(wj_num, round_num) {
            //var round_num = Math.round(Math.random() * 2);
            console.info(round_num);
            if (wj_num === 0 && round_num === 0) {
                $("#img1").attr('src', "./img/gamepj_st.jpg");
                combatscore_update(2);
            } else if (wj_num === 0 && round_num === 1) {
                $("#img1").attr('src', "./img/gamewin_st.jpg");
                combatscore_update(0);
            } else if (wj_num === 0 && round_num === 2) {
                $("#img1").attr('src', "./img/gamelose_st.jpg");
                combatscore_update(1);
            } else if (wj_num === 1 && round_num === 0) {
                $("#img1").attr('src', "./img/gamelose_jd.jpg");
                combatscore_update(1);
            } else if (wj_num === 1 && round_num === 1) {
                $("#img1").attr('src', "./img/gamepj_jd.jpg");
                combatscore_update(2);
            } else if (wj_num === 1 && round_num === 2) {
                $("#img1").attr('src', "./img/gamewin_jd.jpg");
                combatscore_update(0);
            } else if (wj_num === 2 && round_num === 0) {
                $("#img1").attr('src', "./img/gamewin_b.jpg");
                combatscore_update(0);
            } else if (wj_num === 2 && round_num === 1) {
                $("#img1").attr('src', "./img/gamelose_b.jpg");
                combatscore_update(1);
            } else if (wj_num === 2 && round_num === 2) {
                $("#img1").attr('src', "./img/gamepj_b.jpg");
                combatscore_update(2);
            }

            g_wj_num = 99;
            g_round_num = 99;
            initTitleDate();
        }


        var ws = new WebSocket("ws://ali.cnzhanhao.cn:8081");

        ws.onopen = function (evt) {
            console.log("Connection open ...");			
            send_ready();
        };

        //收到消息后判断是自己房间的，就取出判断胜负
        ws.onmessage = function (evt) {
            console.log("Received Message: " + evt.data);
            if (!websocket_msg_patt.test(evt.data)) {
                return;
            }
            var json = JSON.parse(evt.data);
            //收到自己的消息忽略
            if (json.data.userId === uid) {
                return;
            }
            //收到准备指令
            if (json.flag ==="1"&&json.data.roomId === hid&&is_ready===0) {
                send_ready();
                is_ready=1;
                $('a').removeAttr("disabled")
                return;
            }
            //收到退出指令
            if (json.flag === "3"&&json.data.roomId === hid) {
                alert("对方已退出,请重新选择房间");
                window.location.href = "selecthouse.html?id="+uid;
                return;
            }
            //不是本房间的终止
            if (json.flag!="2"||json.data.roomId !== hid) {
                return;
            }
            g_round_num = parseInt(json.data.code);
            if (g_wj_num != 99) {
                iswin(g_wj_num, g_round_num);
            }
        };

        ws.onclose = function (evt) {
            console.log("Connection closed.");
            window.location.href = "selecthouse.html?id="+uid;
        };

        combatscore_add();

        window.onload = function() {            
            $('a').attr('disabled', "true");
        };
    </script>
</head>
<body>
<div class="jumbotron text-center">
    <h1>石头剪刀布，人机争霸战!</h1>
    <em>在线人数统计：</em><em id="totalonline">xxx</em><br> <em>总局数：</em><em
        id="total">xxx</em><br> <em>赢局数：</em><em id="win">xxx</em><br>
    <p></p>
    <p>
        <a class="btn btn-primary btn-lg" href="javascript:send_num(0)"
           role="button">石头</a>
        <a class="btn btn-primary btn-lg"  href="javascript:send_num(1)" role="button">剪刀</a>
        <a class="btn btn-primary btn-lg" href="javascript:send_num(2)"  role="button">布</a>
        <button class="btn btn-primary btn-lg"  onclick="send_exit()">退出房间</button>
    </p>
    <img id="img1" src="./img/initgame.png" class="img-circle">
</div>

</body>
</html>